<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="->">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="userInfo.query"
            clearable
            @clear="getUserLists"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserLists"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeStatus(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editUsers(scope.row.id)"
            ></el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="delUser(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="userInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户区域 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      @close="addUserformColse()"
    >
      <el-form
        :model="addUserForm"
        :rules="addUserFormRules"
        ref="addUserFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户区域 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      @close="editUserformColse()"
    >
      <el-form
        :model="editUserForm"
        :rules="editUserFormRules"
        ref="editUserFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色区域 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRolesdialogVisible"
      width="50%"
      @close="resetInfo"
    >
      <div>
        <p>当前用户名：{{ userDetail.username }}</p>
        <p>当前角色：{{ userDetail.role_name }}</p>
        <p>
          新分配的角色：
          <el-select v-model="selectValue" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer">
        <el-button @click="setRolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveSetRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      const regemail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regemail.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入合法的邮箱'))
      }
    }
    var checkmobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机不能为空'))
      }
      const regmobile =
        /^(0｜86｜17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regmobile.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入合法的手机'))
      }
    }
    return {
      userInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      dialogVisible: false,
      // 添加表单参数
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editUserForm: {},
      editUserFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      setRolesdialogVisible: false,
      userDetail: {},
      roleList: [],
      selectValue: ''
    }
  },
  methods: {
    async getUserLists() {
      const { data: res } = await this.$http.get('users', {
        params: this.userInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      } else {
        this.userList = res.data.users
        this.total = res.data.total
      }
    },
    // 每页条数变化出发
    handleSizeChange(newSize) {
      this.userInfo.pagesize = newSize
      this.getUserLists()
    },
    handleCurrentChange(newPage) {
      this.userInfo.pagenum = newPage
      this.getUserLists()
    },
    async changeStatus(userInfos) {
      const { data: res } = await this.$http.put(
        `users/${userInfos.id}/state/${userInfos.mg_state}`
      )
      if (res.meta.status !== 200) {
        userInfos.mg_state = !userInfos.mg_state
        return this.$message.error('修改状态失败')
      } else {
        return this.$message.success(res.meta.msg)
      }
    },
    addUserformColse() {
      this.$refs.addUserFormRef.resetFields()
    },
    addUsers() {
      this.$refs.addUserFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 200) {
          this.$message.error('添加用户失败')
        }
        this.$message.success(res.meta.msg)
        this.getUserLists()
        this.dialogVisible = false
      })
    },
    async editUsers(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败')
      }
      this.editUserForm = res.data
    },
    editUserformColse() {
      this.$refs.editUserFormRef.resetFields()
    },
    editUserInfo() {
      this.$refs.editUserFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.editUserForm.id,
          {
            email: this.editUserForm.email,
            mobile: this.editUserForm.mobile
          }
        )
        if (res.meta.status !== 200) {
          this.$message.error('修改用户信息失败')
        }
        this.editDialogVisible = false
        this.getUserLists()
        this.$message.success(res.meta.msg)
      })
    },
    // 删除用户
    async delUser(id) {
      const comfireRes = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (comfireRes !== 'confirm') return this.$message.info('已取消')
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getUserLists()
      this.$message.success(res.meta.msg)
    },
    async setRole(info) {
      this.userDetail = info
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status === 200) {
        this.roleList = res.data
      }
      this.setRolesdialogVisible = true
    },
    async saveSetRole() {
      const { data: res } = await this.$http.put(
        `users/${this.userDetail.id}/role`,
        {
          rid: this.selectValue
        }
      )
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
        this.getUserLists()
      }
      this.setRolesdialogVisible = false
    },
    resetInfo() {
      this.selectValue = ''
      this.userDetail = {}
    }
  },
  created() {
    this.getUserLists()
  }
}
</script>
<style lang="less" scoped>
</style>
